package com.fs.common.config;

import com.fs.common.AppConstants;
import com.fs.common.annotations.Auth;
import com.fs.common.annotations.AuthType;
import com.fs.common.bean.UserContextHolder;
import com.fs.common.exception.ForbiddenException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 权限切面
 *
 * @author  LiuQi 2025/6/5-12:07
 * @version V1.0
 **/
@Configuration
@Aspect
@Slf4j
@EnableAspectJAutoProxy
public class AuthAspect {
    @Autowired
    private HttpServletRequest request;

    @Pointcut("@annotation( com.fs.common.annotations.Auth)")
    public void pointCut(){}

    @Before("pointCut()")
    public void log(JoinPoint joinPoint) throws Throwable {
        // 无注解时不处理
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Auth auth = method.getAnnotation(Auth.class);
        if (null == auth) {
            return;
        }

        String tenantId = UserContextHolder.getTenantIdOrThrow();
        if (Arrays.asList(auth.value()).contains(AuthType.SUPER_TENANT)) {
            // 处理超级租户要求的权限
            if (!tenantId.equals(AppConstants.SUPER_TENANT)) {
                throw new ForbiddenException();
            }

            return;
        }
    }
}
